import os
import shutil

import openpyxl

from CommonOperations.get_all_configs import get_local_config
from CommonOperations.parse_img import create_img
from CommonOperations.parse_zip import create_zip_file
from CommonOperations.project_root_path import project_root_path


def create_xlsx_file(dir_path, file_name, sheet_one_name="Sheet1"):
    """
    创建空白xlsx文件
    :param dir_path: 文件夹路径
    :param file_name: 文件名
    :param sheet_one_name: 表名
    :return: 空白xlsx文件路径
    """
    file_path = os.path.join(dir_path, file_name)
    if not os.path.exists(dir_path):
        os.mkdir(dir_path)

    xlsx_file = openpyxl.Workbook()
    xlsx_file.get_active_sheet().title = sheet_one_name

    xlsx_file.save(file_path)
    return file_path


def xlsx_add_sheet(file_path, sheet_title="NewSheet", index=0):
    """
    已有xlsx文件，添加新sheet
    :param file_path: 文件路径
    :param sheet_title: sheet名字
    :param index: sheet索引，默认为0添加到第一张表
    :return:
    """
    xlsx_file = openpyxl.load_workbook(file_path)
    xlsx_file.create_sheet(title=sheet_title, index=index)
    xlsx_file.save(file_path)


def sheet_add_item_value(file_path, sheet_name, item_x, item_y, item_value):
    xlsx_file = openpyxl.load_workbook(file_path)
    choose_sheet = xlsx_file.get_sheet_by_name(sheet_name)
    choose_sheet.cell(row=item_x, column=item_y).value = item_value
    xlsx_file.save(file_path)


def create_xlsx_demo():
    """
    创建xlsx模板文件
    :return: xlsx模板文件路径
    """
    dir_path = os.path.join(project_root_path(), "TemplateDemos")
    file_name = "Demo.xlsx"
    xlsx_demo_path = create_xlsx_file(dir_path, file_name, "配置表")

    file_path = os.path.join(dir_path, xlsx_demo_path)
    xlsx_add_sheet(file_path, "图片列表", 0)
    sheet_add_item_value(file_path, "配置表", 1, 1, "配置信息")
    # 配置表添加默认数据
    setting_sheet_name = "配置表"
    r = 1
    setting_default_data = get_local_config()
    setting_default_data['Dir_setting'] = {"dir_name": "批量文件夹xlsx", "whether_zip": False}
    for section_name, section_list in setting_default_data.items():
        for node_name, node_value in section_list.items():
            sheet_add_item_value(file_path, setting_sheet_name, r, 1, section_name)
            sheet_add_item_value(file_path, setting_sheet_name, r, 2, node_name)
            sheet_add_item_value(file_path, setting_sheet_name, r, 3, node_value)
            r += 1

    # 图片列表添加默认数据
    image_sheet_name = "图片列表"
    img_list = list()
    img_list.append({"name": "图片1", "width": 100, "height": 100})
    img_list.append({"name": "图片2", "width": 200, "height": 100})

    # 先添加第一行表头
    sheet_add_item_value(file_path, image_sheet_name, 1, 1, "name")
    sheet_add_item_value(file_path, image_sheet_name, 1, 2, "width")
    sheet_add_item_value(file_path, image_sheet_name, 1, 3, "height")

    start_r = 2
    for img in img_list:
        sheet_add_item_value(file_path, image_sheet_name, start_r, 1, img['name'])
        sheet_add_item_value(file_path, image_sheet_name, start_r, 2, img['width'])
        sheet_add_item_value(file_path, image_sheet_name, start_r, 3, img['height'])
        start_r += 1

    return xlsx_demo_path


def get_setting_item_value(find_sheet, section_name, node_name):
    """
    读取配置表信息，根据第一、二列数据，获取第三列值
    :param find_sheet: 配置表
    :param section_name: 第一列数据名
    :param node_name: 第二列数据名
    :return: 第三列默认值数据
    """
    for every_row in find_sheet.rows:
        if every_row[0].value == section_name:
            if every_row[1].value == node_name:
                return every_row[2].value


def batch_create_imgs_from_xlsx(file_path):
    """
    根据xlsx配置文件，批量生成图片
    :param file_path: xlsx配置文件路径
    :return:
    """
    xlsx_file = openpyxl.load_workbook(file_path)

    # 获取配置表数据
    setting_sheet_name = "配置表"
    setting_sheet = xlsx_file.get_sheet_by_name(setting_sheet_name)
    default_w = get_setting_item_value(setting_sheet, "Image_setting", "default_w")
    default_h = get_setting_item_value(setting_sheet, "Image_setting", "default_h")
    border_color = get_setting_item_value(setting_sheet, "Image_setting", "border_color")
    border_width = get_setting_item_value(setting_sheet, "Image_setting", "border_width")
    whether_add_border = get_setting_item_value(setting_sheet, "Image_setting", "whether_add_border")
    default_jpg = get_setting_item_value(setting_sheet, "Image_setting", "default_jpg")
    default_png = get_setting_item_value(setting_sheet, "Image_setting", "default_png")
    default_gif = get_setting_item_value(setting_sheet, "Image_setting", "default_gif")

    default_size = get_setting_item_value(setting_sheet, "Font_setting", "default_size")
    default_color = get_setting_item_value(setting_sheet, "Font_setting", "default_color")
    whether_add_text = get_setting_item_value(setting_sheet, "Font_setting", "whether_add_text")

    whether_timestamp = get_setting_item_value(setting_sheet, "Time_setting", "whether_timestamp")

    dir_name = get_setting_item_value(setting_sheet, "Dir_setting", "dir_name")
    whether_zip = get_setting_item_value(setting_sheet, "Dir_setting", "whether_zip")

    # 批量图片文件夹
    batch_imgs_root_dir = os.path.join(project_root_path(), "BatchImages")
    if not os.path.exists(batch_imgs_root_dir):
        os.mkdir(batch_imgs_root_dir)
    batch_imgs_dir = os.path.join(batch_imgs_root_dir, dir_name)
    if not os.path.exists(batch_imgs_dir):
        os.mkdir(batch_imgs_dir)
    # 清空文件夹
    shutil.rmtree(batch_imgs_dir)

    # 获取图片列表清单
    image_sheet_name = "图片列表"
    image_sheet = xlsx_file.get_sheet_by_name(image_sheet_name)

    for every_row in list(image_sheet.rows)[1:]:
        image_name = every_row[0].value
        image_width = every_row[1].value
        image_height = every_row[2].value
        if default_jpg is True:
            create_img(img_width=image_width if image_width > 0 else default_w,
                       img_height=image_height if image_height > 0 else default_h,
                       whether_add_text=whether_add_text,
                       font_color=default_color,
                       font_size=default_size,
                       desc_text=image_name,
                       whether_add_timestamp=whether_timestamp,
                       img_type="JPG",
                       img_dir=batch_imgs_dir,
                       whether_add_border=whether_add_border,
                       border_color=border_color,
                       border_width=border_width)
        if default_png is True:
            create_img(img_width=image_width if image_width > 0 else default_w,
                       img_height=image_height if image_height > 0 else default_h,
                       whether_add_text=whether_add_text,
                       font_color=default_color,
                       font_size=default_size,
                       desc_text=image_name,
                       whether_add_timestamp=whether_timestamp,
                       img_type="PNG",
                       img_dir=batch_imgs_dir,
                       whether_add_border=whether_add_border,
                       border_color=border_color,
                       border_width=border_width)
        if default_gif is True:
            create_img(img_width=image_width if image_width > 0 else default_w,
                       img_height=image_height if image_height > 0 else default_h,
                       whether_add_text=whether_add_text,
                       font_color=default_color,
                       font_size=default_size,
                       desc_text=image_name,
                       whether_add_timestamp=whether_timestamp,
                       img_type="GIF",
                       img_dir=batch_imgs_dir,
                       whether_add_border=whether_add_border,
                       border_color=border_color,
                       border_width=border_width)

    if whether_zip is True:
        zip_path = create_zip_file(batch_imgs_dir)
        return zip_path

    return batch_imgs_dir
